package r929.servletJsonpFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class JsonpResponseWrapper extends HttpServletResponseWrapper {

	private JsonpServletOutputStream outputStream	=	null;
	private PrintWriter writer	=	null;
	private boolean isGetOutputStream	=	false;
	
	public JsonpResponseWrapper(HttpServletResponse response) {
		super(response);
	}
	
	
	@Override
	public void flushBuffer() throws IOException {
		if(writer != null){
			writer.flush();
		}
		if(outputStream != null){
			outputStream.flush();
		}
	}


	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		if(writer != null){
			throw new IllegalStateException();
		}
		
		isGetOutputStream	=	true;
		createOutputStream();
		
		return outputStream;
	}


	@Override
	public PrintWriter getWriter() throws IOException {
		if(isGetOutputStream){
			throw new IllegalStateException();
		}
		
		createOutputStream();
		if(writer == null){
			writer	=	new PrintWriter(outputStream);
		}
		
		return writer;
	}

	
	public void flushBufferToResponse() throws IOException{
		flushBuffer();
		outputStream.flushBufferToServletOutput();
	}
	
	
	public String getJsonResult() throws UnsupportedEncodingException{
		if(outputStream == null)
			return "";
		return outputStream.getJsonResult(getResponse().getCharacterEncoding());
	}
	
	
	
	private void createOutputStream() throws IOException{
		if(outputStream == null){
			outputStream	=	new JsonpServletOutputStream(getResponse().getOutputStream());
		}
	}
}
